﻿using Core;
using Core.Data;
using Core.Domain.Stores;
using Core.Domain.Topics;
using Services.Stores;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Services.Topics
{

    public partial class TopicService : ITopicService
    {
        #region Fields

        private readonly IRepository<Topic> _topicRepository;
        private readonly IRepository<StoreMapping> _storeMappingRepository;
        private readonly IStoreMappingService _storeMappingService;

        #endregion

        #region Ctor

        public TopicService(IRepository<Topic> topicRepository,
            IRepository<StoreMapping> storeMappingRepository,
            IStoreMappingService storeMappingService)
        {
            this._topicRepository = topicRepository;
            this._storeMappingRepository = storeMappingRepository;
            this._storeMappingService = storeMappingService;
        }

        #endregion

        #region Methods

        /// <summary>
        /// 删除主题
        /// </summary>
        public virtual void DeleteTopic(Topic topic)
        {
            if (topic == null)
                throw new ArgumentNullException("topic");

            _topicRepository.Delete(topic);
        }

        /// <summary>
        /// 根据主键获取主题
        /// </summary>
        public virtual Topic GetTopicById(int topicId)
        {
            if (topicId == 0)
                return null;

            return _topicRepository.GetById(topicId);
        }

        /// <summary>
        /// 根据关键字获取主题
        /// </summary>
        public virtual Topic GetTopicBySystemName(string systemName)
        {
            if (String.IsNullOrEmpty(systemName))
                return null;

            var query = _topicRepository.Table;
            query = query.Where(t => t.SystemName == systemName);
            query = query.OrderBy(t => t.Id);
            return query.ToList().FirstOrDefault();
        }

        /// <summary>
        /// 获取所有主题
        /// </summary>
        public virtual IPagedList<Topic> GetAllTopics(int pageIndex, int pageSize)
        {
            var query = _topicRepository.Table;
            query = query.OrderBy(t => t.DisplayOrder);
            return new PagedList<Topic>(query, pageIndex, pageSize);
        }

        /// <summary>
        /// 新增
        /// </summary>
        public virtual void InsertTopic(Topic topic)
        {
            if (topic == null)
                throw new ArgumentNullException("topic");

            _topicRepository.Insert(topic);
        }

        /// <summary>
        /// 更新
        /// </summary>
        public virtual void UpdateTopic(Topic topic)
        {
            if (topic == null)
                throw new ArgumentNullException("topic");

            _topicRepository.Update(topic);
        }

        #endregion
    }
}
